//
//  ChatViewModel.swift
//  Exchange
//
//  Created by rui on 2018/5/9.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class ChatViewModel: NSObject {
    
    var dataArray = [ChatModel]()
    var isOrder: Bool
    
    ///订单id
    var orderId: Int?
    
    ///广告id
    var adId: Int?
    
    var receiver: Int?
    
    var portrait: String? 
    ///待下单id
    var waitOrderId: Int?
    
    var isLoadHistoryData  = false
    
   
    
    typealias Reload = ()->()
    
    var reload: Reload?
    
    var reloadOrderInfo: Reload?
    
    lazy var timeDelt: Double = {
        if let delt = ChatWebScoket.manager.timeDifference {
            return delt
        }
        return 0
    }()
    
    
    init(isOrder: Bool) {
        self.isOrder = isOrder
        super.init()
        ChatWebScoket.manager.delegate = self
        ChatWebScoket.manager.login()
    }
    
    func sendMsg(msg: String)  {
        var req: ChatReq
        if self.isOrder {
            req = ChatReq(cmd: .order)
            req.orderId = orderId
        }else {
            req = ChatReq(cmd: .ad)
            req.advId = adId
            req.receiver = receiver
            req.waitOrderId = waitOrderId
        }
        req.msg = msg
        ChatWebScoket.manager.sendMsg(req: req)
    }
    
    func loadHistoryData() {
        self.isLoadHistoryData = true
        var req: ChatReq
        if self.isOrder {
            req = ChatReq(cmd: .orderHistory)
            req.orderId = orderId
        }else {
            req = ChatReq(cmd: .adHistory)
            req.advId = adId
            req.receiver = receiver
            req.waitOrderId = waitOrderId
        }
        ChatWebScoket.manager.sendMsg(req: req)
    }
    
 
    
    func addTimeModel(models: [ChatModel],finalModel: ChatModel? = nil) {
        autoreleasepool {
            for index in 0..<models.count {
                if index == 0 {
                    if finalModel == nil {
                        dataArray.append(createTimeModel(model: models[index]))
                    } else {
                        if ChatTimeHelper.needAddMinuteModel(preModel: finalModel!, curModel: models[index]) {
                            dataArray.append(createTimeModel(model: models[index]))
                        }
                    }
                } else {
                    if ChatTimeHelper.needAddMinuteModel(preModel: models[index - 1], curModel: models[index]) {
                        dataArray.append(createTimeModel(model: models[index]))
                    }
                }
                dataArray.append(models[index])
            }
        }
    }
    
    fileprivate func createTimeModel(model: ChatModel) -> ChatModel {
        let timeModel: ChatModel = ChatModel()
        timeModel.text = model.text
        timeModel.modelType = .time
        if var time = model.time {
            time = time + self.timeDelt
            timeModel.time = time
            timeModel.timeStr = ChatTimeHelper.chatTimeString(with: timeModel.time)
        }
        timeModel.updateHeight()
        return timeModel
    }
}

extension ChatViewModel: ChatScoketDelegate {

    func webSocket(didReadOrderMsg data: [String:Any]) -> Bool {
        dPrint(data)
        if let orderId = data["orderId"] as? Int,orderId == self.orderId {
            let models = chatModels(data: [data])
            if models.last?.userType == .system {
                self.reloadOrderInfo?()
            }
            addTimeModel(models: models, finalModel: self.dataArray.last)
            self.reload?()
            return true
        }
        return false
    }
    func webSocket(didReadOrderHistoryMsg data: [String:Any]) {
         dPrint(data)
        if let ads = data["historyMessage"] as? [[String:Any]] {
            let models = chatModels(data: ads)
            addTimeModel(models: models, finalModel: self.dataArray.last)
            self.reload?()
        }
    }
    func webSocket(didReadAdMsg data: [String:Any]) -> Bool {
        dPrint(data)
        if let waitOrderId = data["waitOrderId"] as? Int,waitOrderId == self.waitOrderId {
            let models = chatModels(data: [data])
            addTimeModel(models: models, finalModel: self.dataArray.last)
            self.reload?()
            return true
        }
        return false
    }
    
    func webSocket(didReadAdHistoryMsg data: [String:Any]) {
        if let ads = data["historyMessage"] as? [[String:Any]] {
            let models = chatModels(data: ads)
            addTimeModel(models: models, finalModel: self.dataArray.last)
            self.reload?()
        }
    }
    
    func chatModels(data: [[String:Any]]) -> [ChatModel] {
        var models = [ChatModel]()
        autoreleasepool {
            for dic in data {
                let model = ChatModel()
                if let time = dic["createTime"] as? Double {
                    model.time = time / 1000
                }
                model.text = dic["msg"] as? String
                if let sender = dic["sender"] as? Int {
                    if sender == 0 {
                       model.modelType = .system
                       model.userType = .system
                        if let msg = model.text {
                            model.text = kText("系统消息") + ":" + msg
                        }
                    }else if sender == AppInfo.default.userId {
                        model.userType = .me
                        model.avatar = AppInfo.default.portrait
                    }else {
                        model.avatar = portrait
                        model.userType = .friend
                    }
                }
                model.updateHeight()
                models.append(model)
            }
        }
        return models
    }
}
